module.exports = (app) => {
    const router = app.router;
    const Category = app.models.Category;
    /**
     * @apiVersion 1.0.0
     * @apiGroup Catergory
     * @api {get} /categories 获取所有属性
     * @apiParam {String} ids=1,2,3 ids查询
     * @apiParam {String} name name查询
     * @apiParam {Number} parent_id=0 父分类ID
     * @apiParam {Number} with_parent=0 是否携带父级
     * @apiParam {Number} with_children=0 是否携带子分类
     * @apiParam {Number} with_old=0 过滤迁移的老数据
     * @apiParam {Number} level=0 级联数据深度 `eg: 1: {id: 1,children[]}; 2: {id: 1,children: [{id: 2, children: []}]}`
     * @apiSuccessExample Success
     * [{
        bit_id: 1
        created_at: 1555915660
        height: 0 // 画布高
        id: 4884
        is_old: 0
        name: "门店"
        parent_id: 0
        priority: 2
        status: 1
        type: "scene_id"
        unit: "px" // 尺寸单位
        updated_at: 1555915660
        width: 0 画布块
     * }]
     */
    router.get('/categories', function * () {
        const query = this.query;
        if(query.ids) {
            this.body = yield Category.fetchAllByIds(query.ids, true);
            return;
        }

        query.parent_id = query.parent_id || 0;
        query.with_old = query.with_old || 0;

        const level = +query.level || 0;
        const withRelated = [];

        if(query.with_parent && +query.with_parent > 0) {
            withRelated.push('parent');
        }

        if(level > 0 && +query.with_children > 0) {
            const children = [];

            for(let i = 0; i < level; i++) {
                children.push('children');
            }

            withRelated.push(children.join('.'));
        }

        if(query.with_children && +query.with_children > 0) {
            withRelated.push({
                children(qb) {
                    qb.where('deleted', 0);
                    qb.orderBy('priority', 'DESC');

                    if(query.with_debug && +query.with_debug > 0) {
                        qb.where(function() {
                            this.where('status', 1)
                            .orWhere('status', 9);
                        });
                    }
                    else {
                        qb.where('status', 1);
                    }
                },
                'children.children'(qb) {
                    qb.where('deleted', 0);
                    qb.orderBy('priority', 'DESC');

                    if(query.with_debug && +query.with_debug > 0) {
                        qb.where(function() {
                            this.where('status', 1)
                            .orWhere('status', 9);
                        });
                    }
                    else {
                        qb.where('status', 1);
                    }
                }
            });
        }

        const categories = yield Category.query(qb => {
            qb.where('parent_id', query.parent_id);
            qb.where('deleted', Category.NOT_DELETED);

            if(query.status && query.status !== 'all') {
                query.status = query.status || 1;

                qb.where('status', query.status);
            }
            qb.orderBy('priority', 'DESC');
        })
        .fetchAll({
            withRelated: withRelated
        });

        this.body = categories;
    });

     /**
     * @apiVersion 1.0.0
     * @apiGroup Category
     * @api {post} /categories/:id 获取分类详情
     *
     * @apiSuccess {Number} id 分类ID
     * @apiSuccess {Number} parent_id 父级分类ID
     * @apiSuccess {Number} status 上架状态
     * @apiSuccess {String} type 分类类型
     * @apiSuccess {String} resource_type 资源类型
     * @apiSuccess {String} name 分类名字
     * @apiSuccess {String} unit 单位
     * @apiSuccess {Number} width 宽度
     * @apiSuccess {Number} height 高度
     * @apiSuccess {Number} priority 排序优先级
     * @apiSuccessExample Success
     * [{
        bit_id: 1
        created_at: 1555915660
        height: 0 // 画布高
        id: 4884
        is_old: 0
        name: "门店"
        parent_id: 0
        priority: 2
        status: 1
        type: "scene_id"
        unit: "px" // 尺寸单位
        updated_at: 1555915660
        width: 0 画布块
     * }]
     * @apiSampleRequest /categories/1
     */
    router.get('/categories/:id', function * () {
        this.body = yield Category.where({
            deleted: Category.NOT_DELETED,
            id: this.params.id
        })
        .fetch({
            require: true,
            withRelated: ['parent']
        });
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Category
     * @api {post} /categories 创建分类
     *
     * @apiParam {Number} parent_id 父级分类ID
     * @apiParam {Number} status 上架状态
     * @apiParam {String} type 分类类型
     * @apiParam {String} resource_type 资源类型: `poster: 海报, list: 长图 , puzzle: 拼图, movie: 视频, page: 页面`
     * @apiParam {String} name 分类名字
     * @apiParam {Number} priority 排序优先级
     *
     * @apiSampleRequest /categories/1
     */
    router.post('/categories', function * () {
        const body = this.request.body;

        delete body.parent;

        const category = Category.safeForge(body);

        this.body = yield category.save();
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Category
     * @api {put} /categories/:id 修改分类
     *
     * @apiParam {Number} parent_id 父级分类ID
     * @apiParam {Number} status 上架状态
     * @apiParam {String} type 分类类型
     * @apiParam {String} resource_type 资源类型: `poster: 海报, list: 长图 , puzzle: 拼图, movie: 视频, page: 页面`
     * @apiParam {String} name 分类名字
     * @apiParam {Number} priority 排序优先级
     *
     * @apiSampleRequest /categories/1
     */
    router.put('/categories/:id', function * () {
        const body = this.request.body;

        delete body.parent;

        const category = yield Category.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        category.safeSet(body);

        this.body = yield category.save();
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Category
     * @api {delete} /categories/:id 删除分类
     *
     * @apiSampleRequest /categories/1
     */
    router.delete('/categories/:id', function * () {
        yield Category.where({
            id: this.params.id
        })
        .fetch({
            require: true
        })
        .then(model => {
            return model.save({
                deleted: Category.DELETED
            });
        });

        this.body = {
            status: 'success'
        };
    });
};
